import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'

const state = {
  token: getToken(), // 从 缓存 cookie 获取以前token
  userInfo: {}// null undefined 防止后面 userInfo.userid 不报错
}

const getters = {}

const mutations = {
  setToken(state, token) {
    state.token = token
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录
  async login(context, data) {
    const result = await login(data)
    const token = result.data
    context.commit('setToken', token)
    // 存token
    setToken(token)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const result = await getUserInfo()
    // console.log(result)
    context.commit('setUserInfo', result.data)
  },
  // 退出登录
  logout(context) {
    // 清空vuex中token
    context.commit('setToken', '')
    // 清空cookie中的token
    removeToken()
    // 清空vuex中的用户信息
    context.commit('setUserInfo', {})
  }
}

export default {
  // 命名空间
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
